﻿using BleSolution;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YH.Bluetooth;

namespace BleSolution
{
    public partial class Form5 : Form
    {
        private readonly IWebSocketServerService _webSocketServerService;
        private Task _serverTask2;

        /// <summary>
        /// 蓝牙处理核心类
        /// </summary>
        BleCoreNew bleCore = null;
        /// <summary>
        /// 存储检测到的设备
        /// </summary>
        List<Windows.Devices.Bluetooth.BluetoothLEDevice> DeviceList = new List<Windows.Devices.Bluetooth.BluetoothLEDevice>();
        /// <summary>
        /// 当前蓝牙服务列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService> GattDeviceServices = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService>();
        /// <summary>
        /// 当前蓝牙服务特征列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic> GattCharacteristics = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic>();
        public Form5(IWebSocketServerService webSocketServerService)
        {
            try
            {
                LogHelper.WriteLog("程序启动111");
                InitializeComponent();
                _webSocketServerService = webSocketServerService;
                bleCore = new BleCoreNew(_webSocketServerService);

                CheckForIllegalCrossThreadCalls = false;
                this.bleCore.MessAgeChanged += BleCore_MessAgeChanged;
                this.bleCore.DeviceWatcherChanged += BleCore_DeviceWatcherChanged;
                this.bleCore.GattDeviceServiceAdded += BleCore_GattDeviceServiceAdded;
                this.bleCore.CharacteristicAdded += BleCore_CharacteristicAdded;
                this.Init();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }


        /// <summary>
        /// 提示消息
        /// </summary>
        private void BleCore_MessAgeChanged(MsgType type, string message, byte[] data)
        {
            try
            {
                RunAsync(() =>
                {
                    this.lsb_message_list.Items.Add(message);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 获取特征列表
        /// </summary>
        private void BleCore_CharacteristicAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic gattCharacteristic)
        {
            try
            {
                RunAsync(() =>
                {
                    this.cmb_receive_feature_list.Items.Add(gattCharacteristic.Uuid);
                    this.cmb_send_feature_list.Items.Add(gattCharacteristic.Uuid);
                    this.GattCharacteristics.Add(gattCharacteristic);
                    this.btn_listten_receive_feature.Enabled = true;
                    this.btn_check_send_feature.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 获取蓝牙服务列表
        /// </summary>
        private void BleCore_GattDeviceServiceAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService gattDeviceService)
        {
            try
            {
                RunAsync(() =>
                {
                    this.cmb_service_list.Items.Add(gattDeviceService.Uuid.ToString());
                    this.GattDeviceServices.Add(gattDeviceService);
                    this.btn_get_feature.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 搜索蓝牙设备列表
        /// </summary>
        private void BleCore_DeviceWatcherChanged(MsgType type, Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
        {
            try
            {
                RunAsync(() =>
                {
                    this.lsb_device_list.Items.Add(bluetoothLEDevice.Name);
                    this.DeviceList.Add(bluetoothLEDevice);
                    this.btn_match_device.Enabled = true;
                    SendFindReplyDevicesubClass my_sendFindReplyDevicesubClass = new SendFindReplyDevicesubClass();
                    byte[] _Bytes1 = BitConverter.GetBytes(bluetoothLEDevice.BluetoothAddress);
                    Array.Reverse(_Bytes1);
                    string my_device_mac = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                    my_sendFindReplyDevicesubClass.name = bluetoothLEDevice.Name;
                    my_sendFindReplyDevicesubClass.mac = my_device_mac;


                    SendFindReplyDeviceClass my_sendFindReDeviceClass = new SendFindReplyDeviceClass();
                    my_sendFindReDeviceClass.command = CommondCode.find_device_reply.ToString();
                    my_sendFindReDeviceClass.device = my_sendFindReplyDevicesubClass;
                    string my_send_data = JsonConvert.SerializeObject(my_sendFindReDeviceClass);
                    _webSocketServerService.SendMessageToAllAsync(my_send_data);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        // 异步线程
        public static void RunAsync(Action action)
        {
            try
            {
                ((Action)(delegate ()
                {
                    action.Invoke();
                })).BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 初始化界面
        /// </summary>
        private void Init()
        {
            try
            {
                this.btn_match_device.Enabled = false;
                this.btn_get_service.Enabled = false;
                this.btn_get_feature.Enabled = false;
                this.btn_listten_receive_feature.Enabled = false;
                this.btn_check_send_feature.Enabled = false;
                this.btn_send_data.Enabled = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }

        /// <summary>
        /// 打开服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_open_seveice_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击启动服务器按钮");
                if (_serverTask2 == null || _serverTask2.IsCompleted)
                {
                    _serverTask2 = _webSocketServerService.StartAsync();
                    MessageBox.Show("WebSocket 服务器正在启动...");
                    LogHelper.WriteLog("WebSocket 服务器正在启动...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器已经在运行！");
                    LogHelper.WriteLog("WebSocket 服务器已经在运行...");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 服务器-》客户端
        /// 服务器发送扫描设备响应给客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_find_reply_Click(object sender, EventArgs e)
        {
            try
            {
                SendFindReplyDevicesubClass my_sendFindReplyDevicesubClass = new SendFindReplyDevicesubClass();
                my_sendFindReplyDevicesubClass.name = "设备名称1";
                my_sendFindReplyDevicesubClass.mac = "aascasadad";
                SendFindReplyDeviceClass my_sendFindReDeviceClass = new SendFindReplyDeviceClass();
                my_sendFindReDeviceClass.command = CommondCode.find_device_reply.ToString();
                my_sendFindReDeviceClass.device = my_sendFindReplyDevicesubClass;
                string my_send_data = JsonConvert.SerializeObject(my_sendFindReDeviceClass);
                _webSocketServerService.SendMessageToAllAsync(my_send_data);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 点击搜索蓝牙按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_seacher_ble_device_Click(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
    }
}
